#!/bin/bash

HTTPS_CONFIG=''

# 生成负载均衡的upstream配置
INSTANCES=${API_INSTANCES:-1}
BASE_PORT=${API_BASE_PORT:-5002}

echo "Generating upstream configuration for $INSTANCES instances..."

# Create upstream configuration
UPSTREAM_CONFIG="upstream api_servers {"
for i in $(seq 0 $((INSTANCES-1))); do
    PORT=$((BASE_PORT + i))
    UPSTREAM_CONFIG="${UPSTREAM_CONFIG}
    server 172.17.0.1:$PORT;"
done
UPSTREAM_CONFIG="${UPSTREAM_CONFIG}
}"

# Export the upstream configuration as an environment variable
export API_SERVERS="$UPSTREAM_CONFIG"

if [ "${NGINX_HTTPS_ENABLED}" = "true" ]; then
    # Check if the certificate and key files for the specified domain exist
    if [ -n "${CERTBOT_DOMAIN}" ] && \
       [ -f "/etc/letsencrypt/live/${CERTBOT_DOMAIN}/${NGINX_SSL_CERT_FILENAME}" ] && \
       [ -f "/etc/letsencrypt/live/${CERTBOT_DOMAIN}/${NGINX_SSL_CERT_KEY_FILENAME}" ]; then
        SSL_CERTIFICATE_PATH="/etc/letsencrypt/live/${CERTBOT_DOMAIN}/${NGINX_SSL_CERT_FILENAME}"
        SSL_CERTIFICATE_KEY_PATH="/etc/letsencrypt/live/${CERTBOT_DOMAIN}/${NGINX_SSL_CERT_KEY_FILENAME}"
    else
        SSL_CERTIFICATE_PATH="/etc/ssl/${NGINX_SSL_CERT_FILENAME}"
        SSL_CERTIFICATE_KEY_PATH="/etc/ssl/${NGINX_SSL_CERT_KEY_FILENAME}"
    fi
    export SSL_CERTIFICATE_PATH
    export SSL_CERTIFICATE_KEY_PATH

    # set the HTTPS_CONFIG environment variable to the content of the https.conf.template
    export HTTPS_CONFIG=$(envsubst < /etc/nginx/https.conf.template)
else
    export HTTPS_CONFIG=""
fi

if [ "${NGINX_ENABLE_CERTBOT_CHALLENGE}" = "true" ]; then
    export ACME_CHALLENGE_LOCATION='location /.well-known/acme-challenge/ { root /var/www/html; }'
else
    export ACME_CHALLENGE_LOCATION=''
fi

# Get all environment variables for substitution
env_vars=$(printenv | cut -d= -f1 | sed 's/^/$/g' | paste -sd, -)

# Generate all configuration files with environment variables
envsubst "$env_vars" < /etc/nginx/conf.d/default.conf.template > /etc/nginx/conf.d/default.conf
envsubst "$env_vars" < /etc/nginx/nginx.conf.template > /etc/nginx/nginx.conf
envsubst "$env_vars" < /etc/nginx/proxy.conf.template > /etc/nginx/proxy.conf

# Start Nginx using the default entrypoint
exec nginx -g 'daemon off;'